<template name="MyTabs">
  <view class="my_tabs">
    <view class="my_tabs_title">
      <view :class="['my_tabs_item', [item.isActive ? 'active' : '']]" v-for="(item, index) in list" :key="item.id" :data-index="index" @tap="handleItemChange">
        {{ item.name }}
      </view>
    </view>
    <view>
      <view>子组件内的按钮</view>
      <button size="mini" type="primary" @tap="remove">取消子组件监听</button>
    </view>
    <view class="my_tabs_content" v-for="(item, index) in list" :key="item.id" v-show="item.isActive">
      <view class="my_tabs_content_title">{{ item.name }} 页面</view>
      <view class="my_tabs_content_text">{{ item.text !== undefined ? item.text : '没有什么内容' }}</view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MyTabs',
  data() {
    return {
      list: []
    };
  },
  props: {
    tabList: {
      type: Array,
      required: true
    }
  },
  watch: {
    // 监听tabList，如果父组件把它改变，这边也同步一下
    tabList: function() {
      this.list = this.tabList;
    }
  },
  // 生命周期，组件创建完成后被调用
  created() {
    // 创建完成之后，把得到的tabList传给list
    this.list = this.tabList;
    uni.$on('tabChange', this.tabChange);
  },
  //组件销毁后调用
  destroyed() {
    uni.$off('tabChange', this.tabChange);
  },
  methods: {
    remove() {
      uni.$off('tabChange', this.tabChange);
    },
    tabChange: function() {
      console.log('子组件获取事件');
    },
    handleItemChange: function(e) {
      // console.log(e);
      let index = e.currentTarget.dataset.index;
      let list = this.$data.list;
      list.forEach((listItem, listIndex) => {
        // console.log(listIndex,index)
        listIndex == index ? (listItem.isActive = true) : (listItem.isActive = false);
      });
      uni.$emit('tabChange', list);
    }
  }
};
</script>

<style lang="less">
.my_tabs {
  > .my_tabs_title {
    display: flex;
    height: 90rpx;
    > .my_tabs_item {
      display: flex;
      flex: 1;
      justify-content: center;
      align-items: center;
      &.active {
        border-bottom: 2rpx solid red;
      }
    }
  }
  > .my_tabs_content {
    // height: 200rpx;
    border: 6rpx dashed #007aff;
    border-radius: 20rpx;
    > .my_tabs_content_title {
      font-size: 50rpx;
    }
    > .my_tabs_content_text {
      font-size: 32rpx;
      text-indent: 2em;
    }
  }
}
</style>
